import 'package:cached_network_image/cached_network_image.dart';
import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jss_flutter/bean/goods_detail_entity.dart';
import 'package:jss_flutter/widgets/smart_widget.dart';

import 'logic.dart';

///商品详情
class DetailPage extends StatelessWidget {
  final logic = Get.find<DetailLogic>();
  final state = Get.find<DetailLogic>().state;

  DetailPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xfff5f5f5),
      extendBodyBehindAppBar: true,
      body: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: Stack(
          alignment: Alignment.center,
          children: [
            // 未加载前显示的动画，加载之后需要隐藏
            Obx(
              () => loadingWidget(state.loadState.value == 0),
            ),
            Obx(
              () => _goodsDetailWidget(state.loadState.value == 1),
            ),
            Obx(
              () => loadErrorWidget(state.loadState.value == 2),
            ),
          ],
        ),
      ),
    );
  }

  Widget _goodsDetailWidget(bool visible) {
    return Visibility(
      visible: visible,
      child: Column(
        children: [
          _goodsDetailContentWidget(),
          _bottomOptionWidget(),
        ],
      ),
    );
  }

  Widget _goodsDetailContentWidget() {
    return Expanded(
      child: ListView(
        padding: const EdgeInsets.all(0),
        children: [
          Image.network(
            "https://t7.baidu.com/it/u=2621658848,3952322712&fm=193&f=GIF",
            height: 375,
            fit: BoxFit.cover,
          ),
          _goodsInfoWidget(),
          _goodsOptionWidget(),
          Container(
            alignment: Alignment.center,
            margin: const EdgeInsets.fromLTRB(0, 20, 0, 20),
            child: const Text(
              "- 图文详情 -",
              style: TextStyle(
                fontSize: 16,
                color: Color(0xff999999),
              ),
            ),
          ),
          _goodsDetailImage(),
        ],
      ),
    );
  }

  Widget _goodsOptionWidget() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 10),
      padding: const EdgeInsets.symmetric(horizontal: 10),
      decoration: const BoxDecoration(
        //背景
        color: Colors.white,
        //设置四周圆角 角度
        borderRadius: BorderRadius.all(Radius.circular(10)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _goodsCouponWidget(),
          _goodsSkuWidget(),
          _deliveryWidget(),
          _assureWidget(),
        ],
      ),
    );
  }

  Widget _assureWidget() {
    return SizedBox(
      height: 45,
      child: Row(
        children: const [
          Text(
            "保障",
            style: TextStyle(
              fontSize: 16,
              color: Color(0xff333333),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 30),
            child: Text(
              "诚信商家,假一赔四",
              style: TextStyle(
                fontSize: 14,
                color: Color(0xff333333),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _deliveryWidget() {
    return SizedBox(
      height: 45,
      child: Row(
        children: const [
          Text(
            "配送",
            style: TextStyle(
              fontSize: 16,
              color: Color(0xff333333),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 30),
            child: Text(
              "包邮",
              style: TextStyle(
                fontSize: 14,
                color: Color(0xff333333),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _goodsSkuWidget() {
    return SizedBox(
      height: 45,
      child: Row(
        children: const [
          Text(
            "已选",
            style: TextStyle(
              fontSize: 16,
              color: Color(0xff333333),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 30),
            child: Text(
              "36颗装",
              style: TextStyle(
                fontSize: 14,
                color: Color(0xff333333),
              ),
            ),
          ),
          Spacer(),
          Icon(
            Icons.arrow_right,
            color: Colors.grey,
          )
        ],
      ),
    );
  }

  Widget _closeCouponWidget() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15, 0, 15, 10),
      child: ElevatedButton(
        onPressed: () => {Get.back()},
        style: ElevatedButton.styleFrom(
          primary: Colors.red,
          minimumSize: const Size(double.infinity, 45),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
        ),
        child: const Text(
          "关闭",
          style: TextStyle(fontSize: 14, color: Colors.white),
        ),
      ),
    );
  }

  Widget _couponAmountWidget(GoodsDetailDataPlanList item) {
    var amountStr = "";
    if (item.type == 1) {
      amountStr = "¥${Decimal.parse(item.amount).toString()}";
    } else if (item.type == 3) {
      var temp = (item.discount / 10.0).toString();
      amountStr = "${Decimal.parse(temp).toString()}折";
    }
    return SizedBox(
      width: 100,
      child: Text(
        amountStr,
        style: const TextStyle(
          fontSize: 44,
          color: Color(0xffff3300),
        ),
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
    );
  }

  Widget _getCouponStateWidget(GoodsDetailDataPlanList item) {
    return Container(
      width: 56,
      height: 23,
      alignment: Alignment.center,
      decoration: const BoxDecoration(
        //背景
        color: Color(0xffFF3300),
        //设置四周圆角 角度
        borderRadius: BorderRadius.all(Radius.circular(12)),
      ),
      child: Text(
        item.isGet == 0 ? "领取" : "已领取",
        style: const TextStyle(
          fontSize: 12,
          color: Colors.white,
        ),
      ),
    );
  }

  Widget _couponInfoWidget(GoodsDetailDataPlanList item) {
    var condition = "";
    if (item.type == 1) {
      if (item.limitAmount == 0) {
        condition = "无门槛券";
      } else {
        condition = "满${item.limitAmount}可用";
      }
    } else if (item.type == 3) {
      if (item.online == 0) {
        condition = "线下核销";
      } else if (item.online == 1) {
        condition = "线上使用";
      } else {
        condition = "店铺通用";
      }
    }
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.only(left: 15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              item.title,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(
                fontSize: 16,
                color: Color(0xff333333),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 10),
              child: Text(
                condition,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(
                  fontSize: 14,
                  color: Color(0xffff3300),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _couponItemWidget(GoodsDetailDataPlanList item) {
    return Container(
      height: 80,
      margin: const EdgeInsets.fromLTRB(10, 0, 10, 10),
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 15),
      decoration: const BoxDecoration(
        //背景
        color: Color(0xffFFEAE5),
        //设置四周圆角 角度
        borderRadius: BorderRadius.all(Radius.circular(10)),
      ),
      child: Row(
        children: [
          _couponAmountWidget(item),
          _couponInfoWidget(item),
          _getCouponStateWidget(item),
        ],
      ),
    );
  }

  Widget _couponListWidget(List<GoodsDetailDataPlanList> planList) {
    return Expanded(
      child: ListView.builder(
        shrinkWrap: true,
        itemCount: planList.length,
        itemBuilder: (BuildContext context, int index) {
          return _couponItemWidget(planList[index]);
        },
      ),
    );
  }

  Widget _couponWidget(List<GoodsDetailDataPlanList>? planList) {
    return Container(
      decoration: const BoxDecoration(
        //背景
        color: Colors.white,
        //设置四周圆角 角度
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      child: Column(
        children: [
          const Padding(padding: EdgeInsets.only(top: 40)),
          _couponListWidget(planList!),
          _closeCouponWidget(),
        ],
      ),
    );
  }

  Widget _getCouponWidget() {
    return InkWell(
      onTap: () => Get.bottomSheet(
        _couponWidget(state.data.value.planList),
        isDismissible: false,
      ),
      child: Container(
        height: 28,
        width: 70,
        alignment: Alignment.center,
        decoration: const BoxDecoration(
          //背景
          color: Color(0xffff3300),
          //设置四周圆角 角度
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            bottomLeft: Radius.circular(20),
          ),
        ),
        child: const Text(
          "领券 >",
          style: TextStyle(
            fontSize: 14,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  Widget _goodsCouponWidget() {
    return Visibility(
      visible: state.data.value.planList?.isNotEmpty == true,
      child: SizedBox(
        height: 45,
        child: Row(
          children: [
            const Text(
              "优惠",
              style: TextStyle(
                fontSize: 16,
                color: Color(0xff333333),
              ),
            ),
            const Spacer(),
            _getCouponWidget(),
          ],
        ),
      ),
    );
  }

  Widget _goodsInfoWidget() {
    return Container(
      height: 100,
      margin: const EdgeInsets.fromLTRB(10, 10, 10, 10),
      padding: const EdgeInsets.all(10),
      decoration: const BoxDecoration(
        //背景
        color: Colors.white,
        //设置四周圆角 角度
        borderRadius: BorderRadius.all(Radius.circular(10)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              _marketPriceWidget(),
              _originalPriceWidget(),
              const Spacer(),
              _salesWidget(),
            ],
          ),
          _goodsTitleWidget()
        ],
      ),
    );
  }

  Widget _goodsTitleWidget() {
    return Padding(
      padding: const EdgeInsets.only(top: 10),
      child: Text(
        state.data.value.name,
        style: const TextStyle(
          fontSize: 16,
          color: Color(0xff333333),
        ),
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
      ),
    );
  }

  Widget _salesWidget() {
    return Text(
      "销量${state.data.value.sales}",
      style: const TextStyle(
        fontSize: 12,
        color: Color(0xff999999),
      ),
    );
  }

  Widget _originalPriceWidget() {
    return Padding(
      padding: const EdgeInsets.only(left: 5),
      child: Text(
        state.data.value.price,
        style: const TextStyle(
          decoration: TextDecoration.lineThrough,
          fontSize: 12,
          color: Color(0xff999999),
        ),
      ),
    );
  }

  Widget _marketPriceWidget() {
    return Text.rich(
      TextSpan(
        children: [
          const TextSpan(
            text: "¥",
            style: TextStyle(
              fontSize: 14,
              color: Color(0xffff3300),
            ),
          ),
          TextSpan(
            text: state.data.value.marketPrice,
            style: const TextStyle(
              fontSize: 20,
              color: Color(0xffff3300),
            ),
          ),
        ],
      ),
    );
  }

  Widget _goodsDetailImage() {
    return ListView.builder(
      shrinkWrap: true,
      padding: const EdgeInsets.all(0),
      itemCount: state.detailImages.length,
      physics: const NeverScrollableScrollPhysics(),
      itemBuilder: (BuildContext context, int index) {
        return CachedNetworkImage(
          memCacheHeight: 200,
          placeholder: (context, url) =>
              Image.asset('assets/images/default_goods_cover.webp'),
          errorWidget: (context, url, error) =>
              Image.asset('assets/images/default_goods_cover.webp'),
          imageUrl: state.detailImages[index].image,
          width: double.infinity,
          fit: BoxFit.cover,
        );
      },
    );
  }

  Widget _buyNowWidget() {
    return Expanded(
      child: ElevatedButton(
        onPressed: () => {},
        style: ButtonStyle(
          shape: MaterialStateProperty.all(
            const RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                topRight: Radius.circular(20),
                bottomRight: Radius.circular(20),
              ),
            ),
          ),
          backgroundColor: MaterialStateProperty.all(
            const Color(0xffFF3300),
          ),
        ),
        child: const Text(
          "立即购买",
          style: TextStyle(
            color: Colors.white,
            fontSize: 14,
          ),
        ),
      ),
    );
  }

  Widget _joinShoppingCart() {
    return Expanded(
      child: ElevatedButton(
        onPressed: () => {},
        style: ButtonStyle(
          shape: MaterialStateProperty.all(
            const RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                bottomLeft: Radius.circular(20),
              ),
            ),
          ),
          backgroundColor: MaterialStateProperty.all(
            const Color(0xffFFBA12),
          ),
        ),
        child: const Text(
          "加入购物车",
          style: TextStyle(
            color: Colors.white,
            fontSize: 14,
          ),
        ),
      ),
    );
  }

  Widget _bottomOptionIconWidget(
      String title, String resId, GestureTapCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.all(5),
        child: Column(
          children: [
            Image.asset(
              resId,
              width: 20,
              height: 20,
            ),
            Text(
              title,
              style: const TextStyle(
                fontSize: 12,
                color: Color(0xff666666),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _bottomOptionWidget() {
    return Container(
      color: Colors.white,
      height: 50,
      padding: const EdgeInsets.only(right: 10),
      width: double.infinity,
      child: Row(
        children: [
          _bottomOptionIconWidget(
            "店铺",
            "assets/images/icon_store.webp",
            () => {},
          ),
          _bottomOptionIconWidget(
            "客服",
            "assets/images/icon_custom_service.webp",
            () => {},
          ),
          _bottomOptionIconWidget(
            "购物车",
            "assets/images/icon_shopping_cart.webp",
            () => {},
          ),
          Expanded(
            child: Row(
              children: [
                _joinShoppingCart(),
                _buyNowWidget(),
              ],
            ),
          )
        ],
      ),
    );
  }
}
